<?php
/**
 * Created by b17
 * 2/21/12 7:09 PM
 */

namespace Managers;

class Issue extends BaseManager implements CrudManager
{
    const TABLE = '\Catalog\Issue';
    protected $__table = self::TABLE;

    private $_dateFormat = 'Y-m-d';

    const TIME_IN_CACHE = 1800;

    public function getList()
    {
        $res = $this->createQueryBuilder()
            ->addOrderBy('i.id', 'desc')
            ->getQuery()
            ->getArrayResult();

        return $res;
    }

    public function getSelectList()
    {
        $res = $this->getList();
        $elements = array();
        foreach ($res as $item) {
            $elements[] = new SelectElement($item['id'], $item['name']);
        }
        return $elements;

    }

    protected function createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('i')
            ->from($this->__table, 'i')
            ->andWhere('i.isDel = 0');
        return $qb;
    }

    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('i.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    /**
     * Создает новую запись.
     * @param array $values
     */
    public function create(array $values)
    {
        $entity = new \Catalog\Issue();
        $entity->setIsDel(false);
        $this->_setEntityValues($entity, $values);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    private function _setEntityValues(\Catalog\Issue $entity, array $values)
    {
        $entity->setDate(\DateTime::createFromFormat($this->_dateFormat, $values['date']));
        $entity->setIsPublished($values['isPublished']);
        $entity->setName($values['name']);
        if ($values['photoUrl']) {
            $photoUrl = $this->_handleImage($values['photoUrl']);
            $entity->setPhotoUrl($photoUrl);
        }
    }

    private function _handleImage($photoUrl)
    {
        $uploadFile = $this->_getUploadDir() . $photoUrl;
        $params = \Zend_Registry::get('config')->issue->image;
        $saveDir = $this->_getRealPath($params->dir);
        if (!is_writable($saveDir)) {
            throw new \Exception("$saveDir is not writable!");
        }
        $filePath = $this->_getUniqueFile($saveDir, $photoUrl);
        rename($uploadFile, $filePath);
        $cutter = new \Managers\Images\Cutter(new \Managers\Naming\None(), $params->width, $params->height);
        $filePath = $cutter->transform($filePath);
        return Utils::getRelUrl($filePath);
    }



    /**
     * Обновляет запись.
     * @param array $values
     */
    public function update(array $values)
    {
        $entity = $this->find($values['id']);
        $this->_setEntityValues($entity, $values);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    public function getTotal()
    {
        $qb = $this->createQueryBuilder()
            ->select('count(i.id) as total');
        $res = $qb->getQuery()->getArrayResult();
        return $res[0]['total'];
    }
}
